
<!DOCTYPE html>
<html lang="zh-cmn-Hans">

	<head>
		<meta charset="utf-8">
		<meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
		<title>debounce-demo</title>
		<style>
			#container {
				width: 100%;
				height: 200px;
				line-height: 200px;
				text-align: center;
				color: #fff;
				background-color: #444;
				font-size: 30px;
			}
		</style>
	</head>

	<body>
		<div id="container"></div>
		<script>
			function debounce(func, wait, immediate) {
				let timeout, result;

				let debounced = function() {
					var context = this;
					var args = arguments;

					if(timeout) clearTimeout(timeout);
					if(immediate) {
						// 如果已经执行过，不再执行
						var callNow = !timeout;
						timeout = setTimeout(function() {
							timeout = null;
						}, wait)
						if(callNow) result = func.apply(context, args)
					} else {
						timeout = setTimeout(function() {
							func.apply(context, args)
						}, wait);
					}
					return result;
				};

				debounced.cancel = function() {
					clearTimeout(timeout);
					timeout = null;
				};

				return debounced;
			}
			
			let count = 1;
			let container = document.getElementById('container');
			
			function getUserAction() {
			    container.innerHTML = count++;
			};
			
//			container.onmousemove = getUserAction;
			container.onmousemove = debounce(getUserAction,1000); //防抖
		</script>
	</body>

</html>
